package com.yue.excel;

import com.yue.util.PropertyUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayOutputStream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 功能描述: TODO <br/>
 * 创建时间: 2016/9/7<br/>
 *
 * @author QiuYang
 */
public class WriteBuilder {
    private Workbook workbook;
    private int startRow = 0;
    private LinkedHashMap<Integer, Column> columns = new LinkedHashMap<Integer, Column>();

    public WriteBuilder() {
        workbook = new XSSFWorkbook();
    }

    public WriteBuilder column(int index, String colName, ColumnType type) {
        columns.put(index, new Column(colName, type));
        return this;
    }

    public <E extends WriteEntity> byte[] bytesFrom(List<E> datas) {

        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            Map<String, Sheet> sheetMap = new LinkedHashMap<>();
            datas.stream()
                    .map(E::getSheet)
                    .distinct()
                    .collect(Collectors.toList())
                    .forEach(s -> {
                        // 创建sheet
                        Sheet sheet = workbook.createSheet(s);

                        // 创建首行, 文件头
                        Row headRow = sheet.createRow(startRow);
                        columns.forEach((index, column) -> {
                            Cell cell = headRow.createCell(index, Cell.CELL_TYPE_STRING);
                            cell.setCellValue(column.getColName());
                        });
                        sheetMap.put(sheet.getSheetName(), sheet);
                    });

            // 添加数据
            datas.forEach((e) -> {
                String sheetName = e.getSheet();
                Sheet sheet = sheetMap.get(sheetName);
                Row dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
                columns.forEach((index, column) -> {
                    Cell cell = dataRow.createCell(index, Column.getCellType(column.getType()));
                    Object value = PropertyUtil.getProperty(e, column.getColName());   // 反射获取值
//                    Object value = BeanUtils.getProperty(e, column.getColName());
                    cell.setCellValue(value == null ? null : value.toString());
                });
            });


            workbook.write(byteArrayOutputStream);
            return byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
